/*
* Copyright 2011 SmartDocuments. All rights reserved.
* SMARTDOCUMENTS PROPRIETARY/CONFIDENTIAL.
*
*    creation date: Mar 14, 2011
*    version: 1.0
*/
package org.opu.pc.security;

import java.util.ArrayList;
import java.util.Collection;
import org.opu.pc.domain.domains.security.SecurityGroupHolder;
import org.opu.pc.domain.domains.security.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class UserDetailsData implements UserDetails {
	
	private static final long serialVersionUID = 1L;
    private static final SecurityContext context = SecurityContextHolder.getContext();
    
    private User user;
	
	public UserDetailsData(User sdusers) {
        this.user = sdusers;
	}
	
    @Override
	public Collection<GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (SecurityGroupHolder group : user.getSecurityGroups()) {
            authorities.add(new GrantedAuthorityImpl(group.getId().name()));
        }
		return authorities;
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	@Override
	public String getUsername() {
		return user.getName();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;//accountNonExpired;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;//accountNonLocked;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;//credentialsNonExpired;
	}

	@Override
	public boolean isEnabled() {
		return true;//enabled;
	}

    public User getUser() {
        return user;
    }

    public static UserDetailsData getCurrentUser() {
		Authentication auth = context.getAuthentication();
		if (auth != null && auth.getPrincipal() instanceof UserDetailsData) {
			return (UserDetailsData) auth.getPrincipal();
		}
		return null;
	}

    public static void setAuthentication(Authentication authentication) {
        context.setAuthentication(authentication);
	}
    
}
